package ces.lawsuit.plugins;

import java.util.List;

import javax.sql.DataSource;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;

import ces.lawsuit.annotation.TableBind;
import ces.lawsuit.model.BaseModel;
import ces.lawsuit.util.ClassSearcher;
import ces.lawsuit.util.TableNameStyle;

/**
 *表映射插件
 **/
public class AutoTableBindPlugin extends ActiveRecordPlugin {
    private TableNameStyle tableNameStyle;
    private Logger logger=Logger.getLogger(getClass());
 
    public AutoTableBindPlugin(DataSource dataSource) {
        super(dataSource);
    }
 
    public AutoTableBindPlugin(IDataSourceProvider dataSourceProvider, TableNameStyle tableNameStyle) {
        super(dataSourceProvider);
        this.tableNameStyle = tableNameStyle;
    }
 
    @Override
    public boolean start() {
        try {
            List<Class<?>> modelClasses = ClassSearcher.findClasses(BaseModel.class);
            logger.debug("modelClasses.size  modelClasses.size() ");
            TableBind tb = null;
            for (Class modelClass : modelClasses) {
                tb = (TableBind) modelClass.getAnnotation(TableBind.class);
                if (tb == null) {
                    this.addMapping(tableName(modelClass), modelClass);
                  //  logger.debug("auto bindTable: addMapping({}, {})", tableName(modelClass), modelClass.getName());
                } else {
                    if (StrKit.notBlank(tb.pkName())) {
                        this.addMapping(tb.tableName(), tb.pkName(), modelClass);
                       // logger.debug("auto bindTable: addMapping({}, {},{})", new Object[]{tb.tableName(),tb.pkName(), modelClass.getName()});
                    } else {
                        this.addMapping(tb.tableName(), modelClass);
                        //logger.debug("auto bindTable: addMapping({}, {})", tb.tableName(), modelClass.getName());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return super.start();
    }
 
    @Override
    public boolean stop() {
        return super.stop();
    }
 
    private String tableName(Class<?> clazz) {
        String tableName = clazz.getSimpleName();
        if (tableNameStyle == TableNameStyle.UP) {
            tableName = "T_"+tableName.toUpperCase();
        } else if (tableNameStyle == TableNameStyle.LOWER) {
            tableName ="t_"+ tableName.toLowerCase();
        } else {
            tableName ="t_" +StrKit.firstCharToLowerCase(tableName);
        }
        return tableName;
    }
}